$(function(){
    window.global_board = $(".list-control > .title").text();
    $("#select-lists").on("click", function(){
      ischecked = this.checked;
        $(".list-frame").each(function(){
          $(this).children(".list-header").find(".list-deleteckb").attr("checked", ischecked);
        });
    });
    //添加list(input)
    $(".list-add").on("click", function(){
      list_addipt = $(".list-addipt");
      if (list_addipt.css("display")=="none") {
            list_addipt.fadeIn();
            $(this).html("隐藏");
          } else {
            list_addipt.fadeOut("fast");
            $(this).html("+添加List");
          };
    });
    //删除list
    $(".list-delete").on("click", function(){
      del_lists = [];
      $(".list-frame").each(function(){
        list_checked = $(this).children(".list-header").find(".list-deleteckb").is(":checked");
        if (list_checked) {
          del_lists.push($(this).attr("id"));
        };
      });
      if (del_lists.length==0) {
        alert("未选择List");
        return false;};
      if (!confirm("确定删除 "+del_lists.join(", ")+" ？")) {return false;};
      lists_name = JSON.stringify(del_lists);
      $.ajax({
        url:"/list/delete/"+global_board,type:"POST",
        data:{lists_name:lists_name},
        dataType:"json",
        success:function(data){
          if (data["is_delete_ok"]) {
            $.each(del_lists, function(i,val){
              $('.list-frame[id="'+val+'"]').remove();
            });
            alert("删除完成");
          } else {
            alert("未完成");
          };
        },
        error:function(data){
          alert("网络错误");
        }
      });
    });

    $(".list-addipt").on("keyup",function(e){
      if (e.keyCode != 13) return;
      if (!$(this).val()) return;
      var list_name = $(this).val();
      var self = $(this);
        $.ajax({
          //添加list(function)
          url:"/list/create/"+global_board,type:"POST",
          data:{list_name:list_name},dataType:"json",
          success:function(data){
            if (data["is_create_ok"]) {
              add_list = $(_.template($("#list-template").html(), {list_name: list_name})).appendTo("#board-content");
              listview = new ListView({el: add_list});
              self.val('');
            } else {
              alert("添加出错");
            };
          },
          error:function(data){
            alert("网络错误");
          }
        });
    });

      var Card = Backbone.Model.extend({
        urlRoot: "",
        defaults: {
            card_content: "empty_card"
          }
      });

      var ListData = Backbone.Model.extend({
        defaults: {
          list: []
          }
      });

      var CardList = Backbone.Collection.extend({
        url: "empty",
        model: Card
      });

      var CardView = Backbone.View.extend({
        tagName: "li",
        template: _.template($("#card-template").html()),
        events: {
          'click .card-edit': 'edit',
          'click .card-delete': 'clear',
          'keypress .card-editipt': 'updateOnEnter'
        },
        initialize: function() {
          this.listenTo(this.model, 'change', this.render);
          this.listenTo(this.model, 'destroy', this.remove);
        },
        render: function() {
          this.$el.html(this.template(this.model.toJSON()));
          return this;
        },
        edit: function() {
          card_name = this.$(".card-content").text();
          window.global_card = card_name;
          this.$(".card-editipt").val(card_name);
          this.$(".card-content").addClass("content-editing").siblings(".card-editipt").addClass("ipt-editing").select();
        },
        close: function() {
          var this_cardcont = this.$(".card-content");
          var this_cardipt = this.$(".card-editipt");
          var value = this_cardipt.val();
          if (!value || value==global_card) {
            this_cardcont.removeClass("content-editing").siblings(".card-editipt").removeClass("ipt-editing");
          } else {
            this.model.save({card_content: value}, {
            wait: true,
            success: function(model,data){
              if (data['is_recontent_ok']) {
                this_cardipt.val("");
                this_cardcont.removeClass("content-editing").siblings(".card-editipt").removeClass("ipt-editing");
              } else {
                alert("没有重命名");
              };
            },
            error: function(model,data){
              alert("网络错误");
            }
          });
          }
        },
        updateOnEnter: function(e) {
          if (e.keyCode == 13) {
            this.close();
          };
        },
        clear: function() {
          if (confirm("确定删除 "+this.model.get('card_content')+" ？")) {
            this.model.destroy({
            wait: true,
            success: function(model,data){
              if (!data['is_delete_ok']) {
                alert("未删除");
              };
            },
            error: function(model,data){
              alert("网络错误");
            }
          });
          };
        }
      });

      var ListView = Backbone.View.extend({
        events: {
          'click .card-add': 'add_input',
          "keypress .card-addipt": "create_card",
        },
        initialize: function() {
          this.input = this.$(".card-addipt");
          var cards_array = [];
          if (this.model!=undefined) {
            var this_list = this.model.get('list');
            $.each(this_list, function(i,val) {
              var card = new Card(val);
              cards_array.push(card);
            });
          };
          this.collection = new CardList(cards_array);
          this.collection.url = "/card/"+global_board+"/"+this.$(".list-title").text();
          this.listenTo(this.collection, 'add', this.addOne);
          this.listenTo(this.collection, 'reset', this.addAll);
          this.render();
        },
        render: function() {
          var self = this;
          _(this.collection.models).each(function(card){
            self.addOne(card);
          }, this);
        },
        addOne: function(card) {
          var cardview = new CardView({model: card});
          this.$(".list-body").append(cardview.render().el);
        },
        addAll: function() {
          var self = this;
          this.collection.each(self.addOne);
        },
        add_input: function() {
          if (this.input.css("display")=="none") {
            this.input.fadeIn();
            this.$(".card-add").html("隐藏");
          } else {
            this.input.fadeOut("fast");
            this.$(".card-add").html("+新Card");
          };
        },
        create_card: function(e) {
          if (e.keyCode != 13) return;
          if (!this.input.val()) return;
          var this_coll = this.collection;
          var this_input = this.input;
          this_coll.create({card_content: this.input.val()}, {
            wait: true,
            success: function(model,data){
              if (data['is_create_ok']) {
                model.set({id:data['new_card_id']});
                this_input.val('');
              } else {
                alert("未创建");
              };
            },
            error: function(model,data){
              alert("网络错误");
            }
          });
        },
      });

      init_lists = function() {
        $.ajax({
          url:"/board/"+global_board,type:"GET",cache:false,
          data:{get:"all"},dataType:"json",
          success:function(data){
            $.each(data['_lists'], function(i,val) {
              add_list = $(_.template($("#list-template").html(), {list_name: val})).appendTo("#board-content");
              var list_data = new ListData({list: data[val]});
              var listview = new ListView({el: add_list, model: list_data});
            });
          },
          error:function(data){
            alert("网络错误");
          }
        });
      };
      init_lists();
});